import React from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  Image,
  TouchableOpacity,
  Dimensions,
  Platform,
} from 'react-native';
import ImageFooter from './ImageFooter';
import ImageView from 'react-native-image-viewing';
import {Table, Row, Rows} from 'react-native-table-component';
import Utils from '../utils/Utils';
import {BASE_URL} from './BASE_URL';
const {width} = Dimensions.get('window');

let myImages = []; // 预览图片集合
let activeIndex = 0; // 默认从第0张开始预览
export default class RenderDetailsLikeListCell extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
    };
  }

  render() {
    const {listData} = this.props;
    console.log(listData)
    const {visible} = this.state;
    const whiteList = ['jpeg', 'png', 'jpg', 'gif', 'bmp'];
    // 查找当前详情数据里有没有附件
    const obj = listData.filter(
      (item) => item.hasOwnProperty('isFile') && item.isFile,
    );
    // const imgs = listData.filter((item) => item.isFile)
    // 如果有，则取出所有图片类型的附件，并存到图片预览的数组里
    if (obj && obj.length > 0) {
      // const tempObj = JSON.parse(obj.value);
      // console.log('******'+JSON.stringify(obj));
      myImages = [];
      obj
        .map((item) => {
          // console.log(item);
          const list = JSON.parse(item.value);
          // console.log(list instanceof Array);
          if (list instanceof Array) {
            list.map((j) => {
              if (j.fileType && whiteList.includes(j.fileType.toLowerCase())) {
                myImages.push({uri: j.uri});
              }
            });
          } else {
            if (
              list.fileType &&
              whiteList.includes(list.fileType.toLowerCase())
            ) {
              myImages.push({uri: list.uri});
            }
          }
        })
        .filter(Boolean);
      // 绑定图片索引
      myImages.forEach((item, index) => {
        item.index = index;
      });
    }
    // console.log('files', myImages);
    return (
      <View style={{flex: 1, paddingBottom: 10}}>
        <ScrollView
          contentInsetAdjustmentBehavior="automatic"
          style={styles.container}>
          {listData instanceof Array && listData.length > 0 ? (
            this._renderField(listData)
          ) : (
            <Text style={styles.noData}>加载中...</Text>
          )}
        </ScrollView>
        {/* 图片预览插件，原地址：https://github.com/jobtoday/react-native-image-viewing */}
        <ImageView
          images={myImages}
          imageIndex={activeIndex}
          visible={visible}
          onRequestClose={() => {
            this.setState({visible: false});
          }}
          FooterComponent={({imageIndex}) => {
            return (
              <ImageFooter
                imageIndex={imageIndex}
                imagesCount={myImages.length}
              />
            );
          }}
        />
      </View>
    );
  }

  // 渲染一段field
  _renderField(data) {
    console.log(data)
    return data.map((item, index) =>
      item.isTable ? (
        this._renderTableUI(item, index)
      ) : (
        <View style={[styles.item]} key={item.label + index}>
          {/* label */}
          {item.label ? (
            <View style={[styles.letterSpacing, item.labelPanelStyle]}>
              {this._renderLabelWithLetterSpacing(item.label, item)}
            </View>
          ) : null}
          {/* value */}
          <Text style={styles.info}>{this._renderViewWithOwnType(item)}</Text>
        </View>
      ),
    );
  }

  // 渲染label
  _renderLabelWithLetterSpacing(label, item) {
    console.log(label)
    if (label.length <= 7) {
      return (
        <React.Fragment>
          {label.length > 0 ? this._handleChart(label, item) : ''}
        </React.Fragment>
      );
    } else {
      return (
        <Text style={[styles.singleWord, item.labelStyle]}>{label + '：'}</Text>
      );
    }
  }

  // 处理字符串，例：姓名 --> ['姓', '名'] --> <Text>姓</Text><Text>名<T/ext>
  _handleChart(str, item) {
    let newStr = '';
    for (let i = 0; i < str.length; i++) {
      if (i !== str.length - 1) {
        newStr += str[i] + ',';
      } else {
        newStr += str[i] + '：';
      }
    }
    const arr = newStr.split(','); // ['姓', '名']
      console.log(arr)
    return arr.map((c, index) => (
      <Text style={[styles.singleWord, item.labelStyle]} key={c + index}>
        {c}
      </Text>
    ));
  }

  // 渲染value
  _renderViewWithOwnType(item) {
    if (item.hasOwnProperty('isFile') && item.isFile) {
      const list = JSON.parse(item.value);
      return (
        <View style={styles.imageBox}>
          {/* 图片 */}
          <ScrollView
            horizontal={true}
            showsHorizontalScrollIndicator={false}
            style={{width: ((width - 50) * 3) / 4}}>
            {list.map((e, i) => this._renderImage(e, i))}
          </ScrollView>
          {/* 其它附件 */}
          <View
            style={[
              styles.fileBox,
              Platform.OS === 'ios' ? {marginTop: 15} : {},
            ]}>
            {list.map((e, i) => this._renderFile(e, i))}
          </View>
        </View>
      );
    } else {
      return item.value?item.value:'暂无';
    }
  }

  _renderFile(item, i) {
    const fileName = item.fileName;
    const isImage = Utils.checkImage(fileName);
    return !isImage ? (
      <TouchableOpacity
        key={i + '_file_t'}
        activeOpacity={0.8}
        style={[
          styles.fileItem,
          i === 0 && Platform.OS === 'ios' ? {marginTop: -10} : {},
        ]}
        onPress={() => {
          Utils.openBrowserDownloadFile(item.uri, fileName);
        }}>
        {Utils.renderFileIcon(fileName, '#4CBAFC')}
        <Text key={i + '_file'} style={styles.itemInfo}>
          {fileName}
        </Text>
      </TouchableOpacity>
    ) : null;
  }

  // 文件的点击事件和UI表现
  _renderImage(item) {
    const fileName = item.fileName;
    const isImage = Utils.checkImage(fileName);
    return isImage ? (
      <TouchableOpacity
        key={item.uri}
        onPress={() => {
          this._openImageViewDialog(item);
        }}>
        <Image
          style={styles.imageItem}
          source={{uri: item.uri}}
          key={item.uri}
        />
      </TouchableOpacity>
    ) : null;
  }

  // 渲染tableUI
  _renderTableUI(item, index) {
    const data = JSON.parse(item.value);
    return (
      <View key={'table_' + index}>
        <View
          style={[
            styles.letterSpacing,
            item.labelPanelStyle,
            {paddingTop: 15},
          ]}>
          {this._renderLabelWithLetterSpacing(item.label, item)}
        </View>
        <ScrollView horizontal={true} style={{paddingTop: 15}}>
          <Table borderStyle={{borderWidth: 2, borderColor: '#c8e1ff'}}>
            <Row
              data={data.tableHead}
              widthArr={item.widthArr}
              style={styles.head}
              textStyle={styles.text}
            />
            <Rows
              data={data.tableData}
              widthArr={item.widthArr}
              textStyle={[styles.text]}
              style={{maxHeight: 200}}
            />
          </Table>
        </ScrollView>
      </View>
    );
  }

  // 打开图片预览
  _openImageViewDialog(item) {
    const obj = myImages.find((j) => j.uri === item.uri);
    if (obj) {
      activeIndex = obj.index;
    }
    console.log('打开图片预览-activeIndex', activeIndex);
    // 获取打开的图片的索引
    this.setState({
      visible: true,
    });
  }
}

const styles = StyleSheet.create({
  container: {
    paddingLeft: 16,
    paddingRight: 16,
  },
  item: {
    flexDirection: 'row',
    alignItems: 'flex-start',
    paddingTop: 14,
    paddingBottom: 10,
    justifyContent: 'space-between',
    borderBottomWidth: 1,
    borderBottomColor: '#ececec',
  },
  label: {
    fontSize: 16,
    color: '#363636',
  },
  singleWord: {
    fontSize: 16,
    color: '#363636',
  },
  letterSpacing: {
    width: '25%',
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginRight: 20,
  },
  info: {
    // marginLeft: 30,
    // width: '65%',
    flex: 1,
    color: '#828282',
    fontSize: 16,
    // textAlign: 'right',
  },
  imageBox: {
    flexDirection: 'column',
  },
  fileBox: {
    // flex: 1,
  },
  fileItem: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingRight: 5,
    height: 35,
    lineHeight: 35,
  },
  imageItem: {
    width: 60,
    height: 60,
    marginRight: 8,
    marginBottom: 5,
    marginTop: 3,
    borderRadius: 7,
  },
  noData: {
    // textAlign: 'center',
    paddingTop: 50,
    fontSize: 16,
    color: '#6e6b6b',
  },
  head: {
    height: 40,
    backgroundColor: '#f1f8ff',
  },
  text: {
    margin: 10,
    // textAlign: 'center',
  },
});
